package ps

import (
	influx "github.com/influxdata/influxdb1-client/v2"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/sirupsen/logrus"
	"log"
	"time"
	"tym.com/LogCollection/influxdb"
)

type DiskInfo struct {
	usageStat map[string]*disk.UsageStat
}

func getDiskInfo() {
	diskInfo := &DiskInfo{
		usageStat: make(map[string]*disk.UsageStat, 16),
	}
	parts, _ := disk.Partitions(true)
	for _, part := range parts {
		// 拿到每一个分区
		usageStat, err := disk.Usage(part.Mountpoint) // 传挂载点
		if err != nil {
			logrus.Error("get %s usage stat failed, err", err)
			continue
		}
		diskInfo.usageStat[part.Mountpoint] = usageStat
	}
	packDiskPoints(diskInfo)
}

func packDiskPoints(disk *DiskInfo) {
	monitorPoints, err := influx.NewBatchPoints(influx.BatchPointsConfig{
		Database:  "monitor",
		Precision: "s", //精度，默认ns
	})
	if err != nil {
		logrus.Error(err)
	}
	// 根据传入数据的类型插入数据
	for k, v := range disk.usageStat {
		tags := map[string]string{"path": k}
		fields := map[string]interface{}{
			"total":               int64(v.Total),
			"free":                int64(v.Free),
			"used":                int64(v.Used),
			"used_percent":        v.UsedPercent,
			"inodes_total":        int64(v.InodesTotal),
			"inodes_used":         int64(v.InodesUsed),
			"inodes_free":         int64(v.InodesFree),
			"inodes_used_percent": v.InodesUsedPercent,
		}
		pt, err := influx.NewPoint("disk", tags, fields, time.Now())
		if err != nil {
			log.Fatal(err)
		}
		monitorPoints.AddPoint(pt)
		influxdb.PointsSubChan <- monitorPoints
		logrus.Info("ps: insert influx cpu")
	}
}
